package com.lei.leetcode;


import com.lei.datastructure.tree.trie.Trie;

import java.util.TreeMap;

/**
 * @Author LeiXiaoLei
 * @Date 2022/8/30 10:05
 * @Version 1.0
 */
public class S_208 {
    private class Node {
        public boolean isWord;
        public TreeMap<Character, Node> next;

        public Node(boolean isWord) {
            this.isWord = isWord;
            next = new TreeMap<>();
        }

        public Node() {
            this(false);
        }
    }

    private Node root;

    public S_208() {
        root = new Node();
    }

    public void insert(String word) {
        Node current = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (current.next.get(c) == null) current.next.put(c, new Node());
            current = current.next.get(c);
        }
        if (!current.isWord) {
            current.isWord = true;
        }
    }

    public boolean search(String word) {
        Node current = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (current.next.get(c) != null) current = current.next.get(c);
            else return false;
        }
        return current.isWord;
    }

    public boolean startsWith(String prefix) {
        Node current = root;
        for (int i = 0; i < prefix.length(); i++) {
            char c = prefix.charAt(i);
            if (current.next.get(c) == null) return false;
            current = current.next.get(c);
        }
        return true;
    }
}
